package com.image.controller;

import com.alibaba.fastjson.JSONObject;
import com.image.domain.MFile;
import com.image.service.MFileService;
import com.image.utils.DBImageUtils;
import com.image.utils.MultipartFileToFile;
import com.util.Result;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;


/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/7/2 22:59
 * @since JDK 1.8
 */
@RequestMapping("upload")
@RestController
public class UploadFileController {

    @Autowired
    private MFileService mFileService;

    @ApiOperation("文件上传服务模块")
    @RequestMapping(value="/uploadFile",method={RequestMethod.POST})
    @ResponseBody
    public JSONObject uploadFileController(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletResponse response) throws Exception{
        // 转型为MultipartHttpRequest：
      //  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
      //  MultipartFile file= multipartRequest.getFile("file_data");
        if(file==null){
            return Result.error("上传的文件不得为空");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        //文件类型
        String type=fileName.substring(fileName.lastIndexOf(".")+1);
        //文件大小
        Long size1=(file.getSize()/1024)/1024;
        Double size = Double.valueOf(String.valueOf(size1)) ;

        MFile file1=new MFile();
        file1.setFileName(fileName);
        file1.setFileSize(size);
        file1.setFileType(type);
        mFileService.save(file1);

        File file2=MultipartFileToFile.multipartFileToFile(file);
        DBImageUtils.insertImageToDB(file2,file1.getId());
        MultipartFileToFile.delteTempFile(file2);
       JSONObject json=new JSONObject();
        json.put("success", 1);
        json.put("message", "上传成功");
        json.put("url", "/upload/donload/"+file1.getId());
        return json;
    }

    @ApiModelProperty("文件下载id")
    @GetMapping(value = "donload/{fid}")
    public void fileDonloadController(@PathVariable("fid")Integer fid,HttpServletRequest request,HttpServletResponse response) throws Exception{
        InputStream in=DBImageUtils.selectFileById(fid);
        DBImageUtils.readBin2Image2(in,response);
    }

}
